package ynu.elm.controller;

import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import ynu.elm.entity.Food;
import ynu.elm.service.FoodService;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/FoodController")
public class FoodController {

    @Resource
    private FoodService foodService;

    /**
     * 根据商家ID获取商品列表
     * @param businessId 商家ID
     * @return 商品列表
     */
    @GetMapping(value = "/listFoodByBusinessId")
    public List<Food> listFoodByBusinessId(@RequestParam(value = "businessId") Integer businessId){
        List<Food> foods = foodService.selectFoodsByBusinessId(businessId);

        // 确保每个商品都有默认的分类信息
        return foods.stream().map(food -> {
            // 如果remarks为空，设置默认值
            if (food.getRemarks() == null || food.getRemarks().trim().isEmpty()) {
                food.setRemarks("招牌");
            }
            return food;
        }).collect(Collectors.toList());
    }

    /**
     * 根据商家ID获取商品分类列表
     * @param businessId 商家ID
     * @return 分类信息
     */
    @GetMapping(value = "/getCategoriesByBusinessId")
    public List<Map<String, Object>> getCategoriesByBusinessId(@RequestParam(value = "businessId") Integer businessId) {
        List<Food> foods = foodService.selectFoodsByBusinessId(businessId);

        // 按分类分组并统计每个分类的商品数量
        Map<String, Long> categoryCount = foods.stream()
                .collect(Collectors.groupingBy(
                        food -> food.getRemarks() != null && !food.getRemarks().trim().isEmpty() ? food.getRemarks() : "招牌",
                        Collectors.counting()
                ));
        // 转换为前端需要的格式
        return categoryCount.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> category = new java.util.HashMap<>();
                    category.put("categoryId", "cat-" + entry.getKey());
                    category.put("categoryName", entry.getKey());
                    category.put("count", entry.getValue());
                    return category;
                })
                .collect(Collectors.toList());
    }

    /**
     * 根据商品ID获取商品详情
     * @param foodId 商品ID
     * @return 商品详情
     */
    @GetMapping(value = "/getFoodById")
    public Food getFoodById(@RequestParam(value = "foodId") Integer foodId) {
        return foodService.getFoodById(foodId);
    }
}